package com.example.demo.config;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/*
 *
 *   @Author:WE
 *   @Date: 2024/5/8-05-08-20:24
 *   对象存储工具
 */
@Data
@Configuration
//从配置文件中获取配置
@ConfigurationProperties(prefix = "aliyun.oss")
public class OssConfig {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    public OSS getOSSClient(){
        return new OSSClientBuilder().build("https://"+endpoint,accessKeyId,accessKeySecret);
    }

    /**
     * 通用上传文件
     * @param file 文件
     * @param fileType 存放位置
     * @return 上传成功文件地址
     * @throws IOException 流异常
     */
    public String putObject(MultipartFile file,String fileType) throws IOException {
        OSS ossClient = getOSSClient();

        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 创建一个日期时间格式器，用于格式化为"yyyyMMdd"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 格式化当前日期和时间
        String time = now.format(formatter);

        // hutool获取uuid作为文件名
        String simpleUUID = IdUtil.simpleUUID();
        // 获取file 文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        // 上传路径+文件名
        String objectName = time+"/"+fileType+"/"+simpleUUID+"."+suffix;
        // 获取上传文件的输入流
        InputStream inputStream = file.getInputStream();
        // 调用OSS SDK的提交文件
        ossClient.putObject(bucketName, objectName, inputStream);
        // 断开连接
        ossClient.shutdown();
        return time+"/"+fileType+"/"+simpleUUID+"."+suffix;
    }


    /**
     * 下载文件
     * @param objectName 文件名称
     * @return 文件字节数组
     */
    public ByteArrayOutputStream getObject(String objectName) throws IOException {
        //获取链接
        OSS ossClient = getOSSClient();
        // 获取文件输入流
        InputStream inputStream = ossClient.getObject(bucketName, objectName).getObjectContent();

        //输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 1.9+ 的正确写法
        //byte[] buffer = inputStream.readAllBytes();
        //1.8的写法 while循环获取
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        // 断开连接
        ossClient.shutdown();


        return outputStream;
    }

}
